package com.letv.core.parser;

import org.json.JSONException;
import org.json.JSONObject;

import com.alibaba.fastjson.JSON;
import com.letv.core.bean.LetvBaseBean;

/**
 * 主站接口解析器父类
 * <P>
 * { bean:{...}, action:"...", responseType:"...", status:"...", errorCode:"...", message:"..." }
 * 
 * @author zhuqiao
 *
 */
public class LetvMasterParser<T extends LetvBaseBean> extends LetvBaseParser<T, JSONObject> {
    /**
     * 接口信息节点
     * */
    public static final String ACTION = "action";
    /**
     * 接口返回状态：1-正常，2-无数据，3-服务异常，4-数据无变化
     * */
    public static final String RESPONSETYPE = "responseType";
    /**
     * 接口返回数据节点
     * */
    public static final String STATUS = "status";
    /**
     * 接口返回数据节点
     * */
    public static final String ERRORCODE = "errorCode";
    /**
     * 接口返回数据节点
     * */
    public static final String MESSAGE = "message";

    public static final String BEAN = "bean";

    public LetvMasterParser() {
        this(0);
    }

    public LetvMasterParser(int from) {
        super(from);
    }

    @Override
    protected T parse(JSONObject data) throws Exception {
        if (mClz == null || data == null) {
            return null;
        }

        // 默认用gson解析
        return JSON.parseObject(data.toString(), mClz);
    }

    @Override
    protected boolean canParse(String data) {
        try {
            JSONObject object = new JSONObject(data);

            if (!object.has(STATUS)) {
                setErrCode(0);
                return false;
            }

            int status = object.getInt(STATUS);
            int errorCode = object.optInt(ERRORCODE);
            String message = object.optString(MESSAGE);

            setMessage(message);
            setErrCode(errorCode);

            if (status == 1 && errorCode == 0) {
                return true;
            }
        } catch (JSONException e) {
            e.printStackTrace();
        }
        return false;
    }

    @Override
    protected JSONObject getData(String data) throws Exception {
        JSONObject object = new JSONObject(data);
        return object.optJSONObject(BEAN);
    }

}
